package com.mengxin.secondkill.msgqueue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.mengxin.secondkill.message.redisqueue.MsgData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StreamOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisMessageQueue {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 利用Stream推送消息
     * @param key
     * @param value
     * @return
     */
    public String sendMsgStream(String key,Object value){
        StreamOperations<String,String,Object> streamOperations = redisTemplate.opsForStream();
        MapRecord<String,String,Object> objectRecord = null;
        if(value instanceof MsgData){
            objectRecord = StreamRecords
                    .mapBacked(((MsgData) value).msgConvert())
                    .withStreamKey(key);
        }else{
            objectRecord = StreamRecords
                    .mapBacked(Collections.singletonMap("data", value))
                    .withStreamKey(key);
        }
        RecordId recordId = streamOperations.add(objectRecord);
        return recordId.getValue();
    }




    /**
     * 利用list中推送消息
     * @param key
     * @param value
     */
    public void pushMessageList(String key,Object value){
        Preconditions.checkArgument(StringUtils.isBlank(key),"key不能为空");
        redisTemplate.opsForList().leftPush(key,value);
    }


    public Object pollMessageList(String key){
        Preconditions.checkArgument(StringUtils.isBlank(key),"key不能为空");
        return redisTemplate.opsForList().rightPop(key,1000, TimeUnit.MILLISECONDS);
    }
}
